<template>
  <div class="area-list-new">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>{{ currentLocationTitle }}</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport">导出数据</el-button>
            <el-button type="success" @click="handleAddRoot">添加{{ currentLevelText }}</el-button>
          </div>
        </div>
      </template>

      <!-- 当前层级提示 -->
      <div class="level-info" v-if="currentParentId === 0">
        <el-alert type="info" :closable="false" show-icon>
          <template #title>
            当前显示：全国{{ currentLevelText }}列表（共 {{ pagination.total }} 条{{
              currentLevelText
            }}数据）
          </template>
          <template #default>
            点击任意{{ currentLevelText }}右侧的"查看下级"按钮，可查看该{{
              currentLevelText
            }}下属的地区
          </template>
        </el-alert>
      </div>

      <div class="level-info" v-else>
        <el-alert type="info" :closable="false" show-icon>
          <template #title>
            当前显示：{{ breadcrumb.map(b => b.name).join(' > ') }} 的下级地区（共
            {{ pagination.total }} 条数据）
          </template>
          <template #default>点击上方面包屑导航可返回上级，或点击右侧"查看下级"继续深入</template>
        </el-alert>
      </div>

      <!-- 搜索和过滤 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select v-model="searchForm.level" placeholder="选择层级" clearable>
              <el-option label="省份" :value="1" />
              <el-option label="城市" :value="2" />
              <el-option label="区县" :value="3" />
              <el-option label="街道" :value="4" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="输入地区名称搜索"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-col>

          <el-col :span="6">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 面包屑导航 -->
      <div class="breadcrumb-section" v-if="breadcrumb.length > 0">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <el-link @click="handleBreadcrumbClick(null)">全国</el-link>
          </el-breadcrumb-item>
          <el-breadcrumb-item v-for="item in breadcrumb" :key="item.id">
            <el-link @click="handleBreadcrumbClick(item)">{{ item.name }}</el-link>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table :data="tableData" v-loading="loading" border style="width: 100%" height="600">
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="name" label="名称" min-width="200">
            <template #default="{ row }">
              <div class="name-cell">
                <span>{{ row.name }}</span>
                <el-tag v-if="row.has_children" size="small" type="info" class="ml-2">
                  包含 {{ row.children_count || 0 }} 个{{ nextLevelText(row.level) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="level" label="层级" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="levelTagType(row.level)">
                {{ levelText(row.level) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="initial" label="首字母" width="60" />
          <el-table-column prop="pinyin" label="拼音" width="100" />
          <el-table-column prop="citycode" label="城市编码" width="100" />
          <el-table-column prop="adcode" label="区域编码" width="100" />
          <el-table-column prop="lng_lat" label="经纬度" width="120" />
          <el-table-column prop="sort" label="排序" width="80" align="center" />
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.has_children"
                type="primary"
                link
                @click="handleViewChildren(row)"
              >
                查看下级
              </el-button>
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <AreaDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :data="currentArea"
      :parent-id="currentParentId"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { regionApi } from '@/api/system/region'
  import AreaDialog from './components/AreaDialog.vue'

  // 更新接口数据结构，匹配真实的oa_region表字段
  interface AreaItem {
    id: number
    name: string
    parent_id: number
    level: number
    sort: number
    status: number
    initial: string
    pinyin: string
    citycode: string
    adcode: string
    lng_lat: string
    has_children: boolean
    children_count?: number
  }

  // 更新搜索表单接口
  interface SearchForm {
    keyword: string
    level: number | null
    status: number | null
  }

  interface BreadcrumbItem {
    id: number
    name: string
    level: number
  }

  // 响应式数据
  const loading = ref(false)
  const tableData = ref<AreaItem[]>([])
  const breadcrumb = ref<BreadcrumbItem[]>([])
  const currentParentId = ref<number>(0)

  const searchForm = reactive<SearchForm>({
    keyword: '',
    level: null,
    status: null,
  })

  const pagination = reactive({
    current: 1,
    pageSize: 20,
    total: 0,
  })

  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const currentArea = ref<Partial<AreaItem> | null>(null)

  // 计算属性
  const currentLevel = computed(() => {
    if (breadcrumb.value.length === 0) return 1
    return breadcrumb.value[breadcrumb.value.length - 1].level + 1
  })

  const currentLocationTitle = computed(() => {
    if (breadcrumb.value.length === 0) {
      return '全国省市区管理'
    }
    return `${breadcrumb.value.map(b => b.name).join(' - ')} 管理`
  })

  const currentLevelText = computed(() => {
    if (breadcrumb.value.length === 0) return '省级'
    const level = breadcrumb.value[breadcrumb.value.length - 1].level + 1
    return levelText(level)
  })

  // 方法
  const levelText = (level: number): string => {
    const map = { 1: '省份', 2: '城市', 3: '区县', 4: '街道' }
    return map[level as keyof typeof map] || '未知'
  }

  const nextLevelText = (currentLevel: number): string => {
    const map = { 1: '城市', 2: '区县', 3: '街道', 4: '社区' }
    return map[currentLevel as keyof typeof map] || '下级'
  }

  const levelTagType = (level: number): string => {
    const map = { 1: 'primary', 2: 'success', 3: 'warning', 4: 'info' }
    return map[level as keyof typeof map] || 'default'
  }

  const loadData = async () => {
    try {
      loading.value = true
      const params = {
        page: pagination.current,
        limit: pagination.pageSize,
        parent_id: currentParentId.value,
        keyword: searchForm.keyword || undefined,
        level: searchForm.level || undefined,
        status: searchForm.status !== null ? searchForm.status : undefined,
      }

      const response: any = await regionApi.getList(params)
      if (response.code === 0) {
        tableData.value = response.data.list || []
        pagination.total = response.data.total || 0
      } else {
        ElMessage.error(response.msg || '获取数据失败')
      }
    } catch (error) {
      ElMessage.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }

  const handleSearch = () => {
    pagination.current = 1
    loadData()
  }

  const handleReset = () => {
    searchForm.keyword = ''
    searchForm.level = null
    searchForm.status = null
    pagination.current = 1
    loadData()
  }

  const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    loadData()
  }

  const handleCurrentChange = (page: number) => {
    pagination.current = page
    loadData()
  }

  const handleViewChildren = (row: AreaItem) => {
    breadcrumb.value.push({
      id: row.id,
      name: row.name,
      level: row.level,
    })
    currentParentId.value = row.id
    pagination.current = 1
    loadData()
  }

  const handleBreadcrumbClick = (item: BreadcrumbItem | null) => {
    if (!item) {
      breadcrumb.value = []
      currentParentId.value = 0
    } else {
      const index = breadcrumb.value.findIndex(b => b.id === item.id)
      if (index !== -1) {
        breadcrumb.value = breadcrumb.value.slice(0, index + 1)
        currentParentId.value = item.id
      }
    }
    pagination.current = 1
    loadData()
  }

  const handleAddRoot = () => {
    currentArea.value = null
    currentParentId.value = 0
    dialogTitle.value = `添加${currentLevelText.value}`
    dialogVisible.value = true
  }

  const handleEdit = (row: AreaItem) => {
    currentArea.value = row
    dialogTitle.value = '编辑地区'
    dialogVisible.value = true
  }

  const handleDelete = async (row: AreaItem) => {
    try {
      await ElMessageBox.confirm(`确定要删除 "${row.name}" 吗？`, '删除确认', { type: 'warning' })

      const response: any = await regionApi.delete(row.id)
      if (response.code === 0) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }

  const handleStatusChange = async (row: AreaItem, status: number) => {
    try {
      const response: any = await regionApi.setStatus({
        id: row.id,
        status: status,
      })
      if (response.code === 0) {
        ElMessage.success(status === 1 ? '启用成功' : '禁用成功')
      } else {
        ElMessage.error(response.msg || '操作失败')
        // 恢复状态
        row.status = status === 1 ? 0 : 1
      }
    } catch (error) {
      ElMessage.error('操作失败')
      row.status = status === 1 ? 0 : 1
    }
  }

  const handleExport = async () => {
    try {
      loading.value = true

      // 构建导出参数
      const params = {
        parent_id: currentParentId.value,
        keyword: searchForm.keyword || undefined,
        level: searchForm.level || undefined,
        status: searchForm.status !== null ? searchForm.status : undefined,
        export: 1, // 导出标记
      }

      const response: any = await regionApi.getList(params)
      if (response.code === 0 && response.data.list) {
        const exportData = response.data.list

        // 创建CSV内容 - 更新为完整的oa_region表字段
        const headers = [
          'ID',
          '名称',
          '层级',
          '排序',
          '状态',
          '首字母',
          '拼音',
          '城市编码',
          '区域编码',
          '经纬度',
        ]
        const csvContent = [
          headers.join(','),
          ...exportData.map((item: AreaItem) =>
            [
              item.id,
              `"${item.name}"`,
              levelText(item.level),
              item.sort || 0,
              item.status === 1 ? '启用' : '禁用',
              `"${item.initial}"`,
              `"${item.pinyin}"`,
              `"${item.citycode}"`,
              `"${item.adcode}"`,
              item.lng_lat || '',
            ].join(',')
          ),
        ].join('\n')

        // 创建下载链接
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
        const link = document.createElement('a')
        const url = URL.createObjectURL(blob)
        link.setAttribute('href', url)
        link.setAttribute('download', `地区数据_${new Date().toISOString().split('T')[0]}.csv`)
        link.style.visibility = 'hidden'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)

        ElMessage.success('导出成功')
      } else {
        ElMessage.error(response.msg || '导出失败')
      }
    } catch (error) {
      ElMessage.error('导出失败')
    } finally {
      loading.value = false
    }
  }

  const handleSuccess = () => {
    dialogVisible.value = false
    loadData()
  }

  onMounted(() => {
    loadData()
  })
</script>

<style scoped>
  .area-list-new {
    padding: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }

  .level-info {
    margin-bottom: 16px;
  }

  .search-section {
    margin-bottom: 16px;
  }

  .breadcrumb-section {
    margin-bottom: 16px;
    padding: 12px;
    background-color: #f5f5f5;
    border-radius: 4px;
  }

  .table-section {
    margin-bottom: 16px;
  }

  .name-cell {
    display: flex;
    align-items: center;
  }

  .ml-2 {
    margin-left: 8px;
  }

  .pagination-section {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }
</style>

// 更新表单数据结构，匹配oa_region表字段 const form = reactive({ id: undefined as number |
undefined, parent_id: 0, level: 1, name: '', initial: '', pinyin: '', citycode: '', adcode: '',
lng_lat: '', sort: 0, status: 1 }) // 初始化表单数据 - 更新字段映射 const initForm = () => { form.id
= undefined form.parent_id = currentParentId.value form.level = currentLevel.value form.name = ''
form.initial = '' form.pinyin = '' form.citycode = '' form.adcode = '' form.lng_lat = '' form.sort =
0 form.status = 1 } // 监听对话框打开 watch(dialogVisible, (val) => { if (val) { if
(currentArea.value) { // 编辑模式 Object.assign(form, currentArea.value) } else { // 新增模式
initForm() } } })
